package com.smy.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smy.reggie.common.CustomException;
import com.smy.reggie.dao.SetmealMapper;
import com.smy.reggie.dto.SetmealDto;
import com.smy.reggie.pojo.Setmeal;
import com.smy.reggie.pojo.SetmealDish;
import com.smy.reggie.service.SetmealDishService;
import com.smy.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 双表添加
     * @param dto
     */
    @Override
    @Transactional
    public void addWhitDish(SetmealDto dto) {
        //保存到套餐表
        this.save(dto);
        //获取前端所选菜品对象
        List<SetmealDish> setmealDishes = dto.getSetmealDishes();
        //重新加工前端所选菜品对象
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(dto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存到套餐菜品关系表
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    @Transactional
    public void deleteWhitDish(List<Long> ids) {
        //如果为停售状态才可以删除
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId,ids);
        wrapper.eq(Setmeal::getStatus,1);//查询所有在售的
        Long count = this.count(wrapper);
        if (count > 0) {//如果没有停售的
            throw new CustomException("套餐须停售才可删除！");
        }
        this.removeByIds(ids);
        //删除关系表
        LambdaQueryWrapper<SetmealDish> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(SetmealDish::getSetmealId,ids);
        setmealDishService.removeByIds(ids);

    }
}
